# -*- coding: utf-8 -*-
"""
@Time: 2025/2/21 11:34
@File: upload.py
@IDE: PyCharm
@Auth: Kendrick.Kc.Guan
@Email: 509556985@qq.com
@Version: 1.0
"""


import time
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings


class Upload(APIView):

    def post(self, request, *args, **kwargs):
        res_file = request.FILES.get('file', None)
        if not res_file:
            return Response({'code': 401, 'msg': '请上传文件'})
        file_name = f'{str(int(time.time() * 1000))}_{res_file.name}'
        with open(f'{settings.MEDIA_ROOT}{settings.UPLOAD_PATH}{file_name}', 'ab') as fp:
            for part in res_file.chunks():
                fp.write(part)
        return Response({'code': 200, 'msg': 'ok', 'data': {'url': f'{settings.MEDIA_URL}{settings.UPLOAD_PATH[1:]}{file_name}'}})